import Shop from '../../model/shop'
import Orders from '../../model/orders'
import DlyAdminUser from '../../model/dlyadminuser'

import DlyAdminLinkClick from '../../model/dlyadminlinkclick'
import mongoose from 'mongoose'
import moment from 'moment'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
class HomeController {
	static async shareLinkData(ctx) {
		const { roleName = '', _id = '' } = ctx.header.jwtuserinfo
        console.log('ctx.header.jwtuserinfo', ctx.header.jwtuserinfo)
		const responsdata = {
			linkData: [],
			shopData: [],
			orderData: [],
		}
		switch (roleName) {
			case 'adminSp':
				// 获取全部的链接点击数量
				responsdata.linkData = await getDataFun()
				// 获取全部的新增用户数量
				responsdata.shopData = await getShopDataLength()
				// 获取全部订单数量
                // const getPriterlist = await DlyAdminUser.find({
				// 	parentId: _id,
				// }).limit(1000)
				// let getids = [_id]
				// if (getPriterlist) {
				// 	getPriterlist.forEach((res) => {
				// 		getids.push(res._id)
				// 	})
				// }
				responsdata.orderData = await getOrderDataLength()
				break
			case 'admin':
				// 获取全部的链接点击数量
				responsdata.linkData = await getDataFun()
				responsdata.shopData = await getShopDataLength()
                responsdata.orderData = await getOrderDataLength()
				break
			case 'proxy1':
				// 还需要显示子代理的所有数据
				const getPriterlist = await DlyAdminUser.find({
					parentId: _id,
				}).limit(1000)
				console.log('getPriterlist', getPriterlist)
				let getids = [_id]
				if (getPriterlist) {
					getPriterlist.forEach((res) => {
						getids.push(res._id)
					})
				}
				responsdata.linkData = await getDataFun(getids)
				responsdata.shopData = await getShopDataLength(getids)
                responsdata.orderData = await getOrderDataLength(getids)
				break
			case 'proxy2':
				getids = [_id]
				responsdata.linkData = await getDataFun(getids)
				responsdata.shopData = await getShopDataLength(getids)
                responsdata.orderData = await getOrderDataLength(getids)
				break

			default:
				throw new ApiError(ApiErrorNames.UnknownError)
		}
		ctx.body = responsdata
		async function getDataFun(ids) {
			// 分享链接点击次数
			const sevenDaysAgo = new Date()
			sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
			sevenDaysAgo.setHours(0, 0, 0, 0)
			const sheachdata = {}
			try {
				if (ids) {
					sheachdata.proxyId = {
						$in: ids.map((id) => {
							return mongoose.Types.ObjectId(id)
						}),
					}
				}
			} catch (error) {}
			const result = await DlyAdminLinkClick.aggregate([
				{
					$match: {
						createDate: {
							$gte: sevenDaysAgo,
							$lte: new Date(),
						},
						...sheachdata,
						// proxyId: mongoose.Types.ObjectId(id)
					},
				},
				{
					$group: {
						_id: '$createDate',
						todayCount: { $sum: 1 },
					},
				},
			])
			// console.log('result', result)
			return result
		}
		async function getShopDataLength(ids) {
			const sevenDaysAgo = new Date()
			sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
			sevenDaysAgo.setHours(0, 0, 0, 0)
			const sheachdata = {}
            // console.log('ids', ids)
			try {
				if (ids) {
					sheachdata.proxyId = {
						$in: ids.map((id) => {
							return mongoose.Types.ObjectId(id)
						}),
					}
				}
			} catch (error) {}
            // console.log('sheachdata.proxyIdshop', sheachdata )
			const result = await Shop.aggregate([
				{
					$match: {
						createDate: {
							$gte: sevenDaysAgo,
							$lte: new Date(),
						},
						...sheachdata,
						// proxyId: mongoose.Types.ObjectId(id)
					},
				},
				{
					$group: {
						_id: '$createDate',
						todayCount: { $sum: 1 },
					},
				},
			])
			console.log('result123', result)
			return result
		}
		async function getOrderDataLength(ids) {
			const sevenDaysAgo = new Date()
			sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
			sevenDaysAgo.setHours(0, 0, 0, 0)
			const sheachdata = {}

            try {
				if (ids) {
					// console.log('ids', ids)
                    // const proxyShops =  await Shop.find().limit(2000)
					// proxyShops.forEach((item) => {
					//     console.log('item', item)
					// 	// 更新createDate 为createTime
					// 	item.createDate = moment(item.createTime).format('YYYY-MM-DD')
					// 	item.save()
					// })
                    // const shopIds = proxyShops.map(item => item.shop_id)
					// // console.log('proxyShops', proxyShops, shopIds)
                    // // shopIds.push('123456')
                    // const ordershops = await Orders.find({shop_id: {$in: shopIds}})
					// console.log('ordershops', ordershops)
					// 批量更新proxyId
					// Orders.updateMany({shop_id: {$in: shopIds}}, {proxyId: mongoose.Types.ObjectId(ids[0])}, function(err, docs) {
					    
					
					// })

					
					sheachdata.proxyId = {
						$in: ids.map((id) => {
							console.log('id', id)
							return mongoose.Types.ObjectId(id)
						}),
					}
				}
				console.log('sheachdata.proxyIdshop1112', sheachdata )
				const result = await Orders.aggregate([
					{
						$match: {
							createDate: {
								$gte: sevenDaysAgo,
								$lte: new Date(),
							},
							...sheachdata
						},
					},
					{
						$group: {
							_id: '$createDate',
							todayCount: { $sum: 1 },
							allPayAmount: { $sum: '$pay_amount' },
						},
					},
				])
				console.log('result', result)
			return result

			} catch (error) {
				console.log('error', error)
			}
			// console.log('123456', sheachdata)
          
			// console.log('result123456', result)

		}
	}
}

export default HomeController
